<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item prop="name" label="用户名称">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入用户名称"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item prop="title" label="问题名称">
          <el-input
            v-model="queryParams.title"
            placeholder="请输入问题名称"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item prop="gender" label="性别">
          <el-select
            v-model="queryParams.gender"
            placeholder="请选择性别"
            clearable
            style="width: 220px"
          >
            <el-option label="男" value="male" />
            <el-option label="女" value="female" />
            <el-option label="未知" value="unknown" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="mb-10px">
        <el-button type="danger" :disabled="ids.length === 0" icon="delete" @click="handleDelete()">
          删除
        </el-button>
        <el-button type="warning" icon="upload" @click="handleImportDialog">导入Excel</el-button>
        <el-button type="primary" icon="download" @click="handleExportExcel">导出Excel</el-button>
      </div>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="dataList"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="用户名称" align="center" prop="name" width="120" />
        <el-table-column label="用户头像" align="center" width="120">
          <template #default="scope">
            <el-avatar :src="scope.row.avatar_url" />
          </template>
        </el-table-column>
        <el-table-column label="性别" align="center" prop="gender" width="80">
          <template #default="scope">
            <el-tag v-if="scope.row.gender === 'male'" type="primary">男</el-tag>
            <el-tag v-else-if="scope.row.gender === '-1'" type="danger">女</el-tag>
            <el-tag v-else type="info">未知</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="问题名称" align="center" prop="title" min-width="180" />
        <el-table-column label="评论内容" align="center" prop="excerpt" min-width="350" />
        <el-table-column label="点赞数" align="center" prop="voteup_count" width="100" />
        <el-table-column label="回复数" align="center" prop="reply_count" width="100" />
        <el-table-column label="浏览数" align="center" prop="view_count" width="100" />
        <el-table-column label="评论数" align="center" prop="comment_count" width="100" />
        <el-table-column label="喜欢数" align="center" prop="favorites_count" width="100" />
        <el-table-column label="创建时间" align="center" prop="created_time" width="180">
          <template #default="scope">
            {{ formatTime(scope.row.created_time) }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" align="center" label="操作" width="130">
          <template #default="scope">
            <el-button
              type="danger"
              size="small"
              link
              icon="delete"
              @click="handleDelete(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>

    <!-- Excel导入弹窗 -->
    <el-dialog v-model="importDialog.visible" title="导入Excel" width="500px">
      <el-upload
        ref="uploadRef"
        class="upload-demo"
        action=""
        :limit="1"
        :auto-upload="false"
        :on-change="handleFileChange"
        :file-list="importDialog.fileList"
        accept=".xlsx,.xls"
      >
        <template #trigger>
          <el-button type="primary">选择文件</el-button>
        </template>
        <el-button class="ml-3" type="success" @click="submitUpload">导入</el-button>
        <template #tip>
          <div class="el-upload__tip">
            请上传Excel文件，支持.xlsx和.xls格式
            <el-link
              type="primary"
              :underline="false"
              @click="downloadTemplate"
              style="margin-left: 10px"
            >
              下载模板
            </el-link>
          </div>
        </template>
      </el-upload>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import * as XLSX from "xlsx";
import BaseDataAPI from "@/api/BaseData"; // 更新API引用
import { formatTime } from "@/utils/time";
const queryFormRef = ref();
const uploadRef = ref();
const loading = ref(false);
const ids = ref<number[]>([]);
const total = ref(0);

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  name: "",
  title: "",
  gender: "",
});

// 表格数据
const dataList = ref<any[]>([]);

// 导入弹窗
const importDialog = reactive({
  visible: false,
  fileList: [],
  fileRaw: null,
});

// 查询数据
function handleQuery() {
  loading.value = true;
  BaseDataAPI.getPage(queryParams)
    .then((data) => {
      dataList.value = data.list;
      total.value = data.total;
    })
    .finally(() => (loading.value = false));
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

// 行复选框选中
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.id);
}

// 删除记录
function handleDelete(id?: number) {
  const deleteIds = [id || ids.value].join(",");
  if (!deleteIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      BaseDataAPI.deleteByIds(deleteIds)
        .then(() => {
          ElMessage.success("删除成功");
          handleQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

// 打开导入弹窗
function handleImportDialog() {
  importDialog.visible = true;
  importDialog.fileList = [];
  importDialog.fileRaw = null;
}

// 文件选择变化
function handleFileChange(file: any) {
  importDialog.fileRaw = file.raw;
}

// 提交导入
function submitUpload() {
  if (!importDialog.fileRaw) {
    ElMessage.warning("请先选择文件");
    return;
  }

  loading.value = true;
  const reader = new FileReader();
  reader.onload = (e) => {
    const data = new Uint8Array(e.target?.result as ArrayBuffer);
    const workbook = XLSX.read(data, { type: "array" });
    const firstSheetName = workbook.SheetNames[0];
    const worksheet = workbook.Sheets[firstSheetName];
    const jsonData = XLSX.utils.sheet_to_json(worksheet);

    // 转换数据格式
    const importData = jsonData.map((item: any) => ({
      name: item["用户名称"],
      avatar_url: item["用户头像"],
      gender: item["性别"] === "男" ? "male" : item["性别"] === "女" ? "female" : "unknown",
      title: item["问题名称"],
      excerpt: item["评论内容"],
      voteup_count: item["点赞数"] || 0,
      reply_count: item["回复数"] || 0,
      view_count: item["浏览数"] || 0,
      comment_count: item["评论数"] || 0,
      favorites_count: item["喜欢数"] || 0,
      created_time: item["创建时间"] || new Date().toISOString(),
    }));

    // 批量导入
    BaseDataAPI.batchImport(importData)
      .then(() => {
        ElMessage.success(`成功导入${importData.length}条数据`);
        importDialog.visible = false;
        handleQuery();
      })
      .catch(() => {
        ElMessage.error("导入失败，请检查数据格式");
      })
      .finally(() => {
        loading.value = false;
      });
  };
  reader.readAsArrayBuffer(importDialog.fileRaw);
}

// 导出Excel
function handleExportExcel() {
  loading.value = true;
  BaseDataAPI.getAll(queryParams)
    .then((data) => {
      const exportData = data.map((item: any) => ({
        用户名称: item.name,
        用户头像: item.avatar_url,
        性别: item.gender === "male" ? "男" : item.gender === "female" ? "女" : "未知",
        问题名称: item.title,
        评论内容: item.excerpt,
        点赞数: item.voteup_count,
        回复数: item.reply_count,
        浏览数: item.view_count,
        评论数: item.comment_count,
        喜欢数: item.favorites_count,
        创建时间: formatTime(item.created_time),
      }));

      const worksheet = XLSX.utils.json_to_sheet(exportData);
      const workbook = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(workbook, worksheet, "基础数据");
      XLSX.writeFile(workbook, `基础数据_${new Date().toLocaleDateString()}.xlsx`);
    })
    .catch(() => {
      ElMessage.error("导出失败");
    })
    .finally(() => {
      loading.value = false;
    });
}

// 下载模板
function downloadTemplate() {
  const templateData = [
    {
      用户名称: "张三",
      用户头像: "https://example.com/avatar1.jpg",
      性别: "男",
      问题名称: "示例问题",
      评论内容: "示例评论内容",
      点赞数: 10,
      回复数: 5,
      浏览数: 100,
      评论数: 8,
      喜欢数: 3,
      创建时间: "2023-01-01 10:00:00",
    },
  ];

  const worksheet = XLSX.utils.json_to_sheet(templateData);
  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, worksheet, "模板");
  XLSX.writeFile(workbook, "基础数据导入模板.xlsx");
}

onMounted(() => {
  handleQuery();
});
</script>

<style lang="scss" scoped>
.app-container {
  position: relative;
  padding: 24px;
}

.search-bar {
  margin-bottom: 20px;
}

.mb-10px {
  margin-bottom: 10px;
}

.mt-10px {
  margin-top: 10px;
}

.ml-3 {
  margin-left: 12px;
}

.upload-demo {
  text-align: center;
}
</style>
